//
//  PostListVC.m
//  sensen_ios
//
//  Created by mc on 16/3/3.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "PostListVC.h"

// 单元格
#import "PostBrowseCell.h" // 帖子概览单元格

#import "PostDetailVC.h"

#import "PostModel.h"
#import "PostReplyModel.h"

#import "CommentBottomCell.h"
#import "PostPictureCell.h"
#import "PostContentCel.h"
#import "PostTitleCell.h"
#import "PostReplyCell.h"
#import "PostReplyPictureCell.h"
#import "ZKTextImgReplaceHandle.h"


#define Margin 13
#define LeftMargin 16


@interface PostListVC ()<UITableViewDataSource, UITableViewDelegate>{
    
    UITableView *_tableView; // 表视图
    UIView *_emptyView;//空视图
    NSInteger _page_no;//页码
    NSInteger _page_size;//页面元素个数
    
}

@property (nonatomic, strong) NSMutableArray *itemsAry;


@end

@implementation PostListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self _initTableView];
    
    [self _getData];

    
    // 刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_getData)];
    _tableView.header = header;
    
    
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    NSLog(@"type = %ld", (long)self.type);

    [self _getData];
}



#pragma mark - 获取数据

- (void)_getData {
    NSString * url ;
    NSMutableDictionary *diction = [NSMutableDictionary dictionaryWithCapacity:1];
    UserModel *user = [CommonCache getUserInfo];
    if (self.type == 0) {//查看我的主题帖
        url = @"BY_BbsUserCenter_queryThread";
        //[diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 1){//查看我的帖子
        url = @"BY_BbsUserCenter_queryPost";
        //[diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 2){//查看我的评论
        url = @"BY_BbsUserCenter_queryComment";
       // [diction setObject:@"18" forKey:@"uid"];
    }else if (self.type == 3){//查看主题回复
        url = @"BY_BbsUserCenter_replyThread";
       // [diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 4){//查看帖子评论
        url = @"BY_BbsUserCenter_replyPost";
       // [diction setObject:@"27" forKey:@"uid"];
    }
    
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
    
    _page_size = 10;
    _page_no = 1;
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_no] forKey:@"page_no"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_size] forKey:@"page_size"];
    [diction setObject:user.uid forKey:@"uid"];
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:url apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"主题帖分页查询%@", result);
        if (weakSelf.itemsAry == nil) {
            weakSelf.itemsAry = [NSMutableArray array];
        }else{
            [weakSelf.itemsAry removeAllObjects];
        }
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary * diction in result[@"list"]) {
                if (self.type == 0) {
                    PostModel *model = [[PostModel alloc] initContentWithDic:diction];
                    [weakSelf.itemsAry addObject:model];
                }else {
                    PostReplyModel *model = [[PostReplyModel alloc] initContentWithDic:diction];
                     [weakSelf.itemsAry addObject:model];
                }
                
            }
          
               _tableView.hidden = NO;
              _emptyView .hidden = YES;
            
        }else{
            
            _tableView.hidden = YES;
            _emptyView .hidden = NO;
        }
     
        if (weakSelf.itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }

        
        [_tableView.header endRefreshing];
        [SVProgressHUD dismiss];
         [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
          [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
        [_tableView.header endRefreshing];
    }];
   
}

- (void)_getMoreData{
    
    NSString * url ;
    UserModel *user = [CommonCache getUserInfo];
     NSMutableDictionary *diction = [NSMutableDictionary dictionaryWithCapacity:1];
    if (self.type == 0) {//查看我的主题帖
        url = @"BY_BbsUserCenter_queryThread";
        //[diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 1){//查看我的帖子
        url = @"BY_BbsUserCenter_queryPost";
        //[diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 2){//查看我的评论
        url = @"BY_BbsUserCenter_queryComment";
        //[diction setObject:@"18" forKey:@"uid"];
    }else if (self.type == 3){//查看主题回复
        url = @"BY_BbsUserCenter_replyThread";
        //[diction setObject:@"6" forKey:@"uid"];
    }else if (self.type == 4){//查看帖子评论
        url = @"BY_BbsUserCenter_replyPost";
        //[diction setObject:@"27" forKey:@"uid"];
    }
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
   
    _page_size = 10;
    _page_no += 1;
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_no] forKey:@"page_no"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_size] forKey:@"page_size"];
    [diction setObject:user.uid forKey:@"uid"];
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:url apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"%@", result);
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary * diction in result[@"list"]) {
                if (self.type == 0) {
                    PostModel *model = [[PostModel alloc] initContentWithDic:diction];
                    [weakSelf.itemsAry addObject:model];
                }else {
                    PostReplyModel *model = [[PostReplyModel alloc] initContentWithDic:diction];
                    [weakSelf.itemsAry addObject:model];
                }
                
            }
            
        }
        if (weakSelf.itemsAry.count == 0) {
            _tableView.hidden = YES;
            _emptyView .hidden = NO;

        }else{
            _tableView.hidden = NO;
            _emptyView .hidden = YES;

        }
        
    
        if (weakSelf.itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }else{
            [_tableView.footer endRefreshing];
        }

        [SVProgressHUD dismiss];
         [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_tableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];

}

// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 -36) style:UITableViewStyleGrouped];
    _tableView.scrollEnabled = YES;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    //_tableView.hidden = YES;

    _emptyView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _tableView.height)];
    [self.view addSubview:_emptyView];

    UILabel *lable = [[UILabel alloc] init];
    [_emptyView addSubview:lable];
    _emptyView.hidden = YES;
   [lable mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.equalTo(_emptyView.mas_centerX).offset(0);
       make.centerY.equalTo(_emptyView.mas_centerY).offset(-100);
       make.size.mas_equalTo(CGSizeMake(200, 20));
   }];
    
    
    lable.text = @"您还没有发布任何内容额";
    lable.textColor = [UIColor lightGrayColor];
    lable.font = [UIFont systemFontOfSize:13];
    lable.textAlignment = NSTextAlignmentCenter;
    
    UILabel *lable1 = [[UILabel alloc] init];
    [_emptyView addSubview:lable1];
    
    [lable1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX).offset(0);
        make.top.equalTo(lable.mas_bottom).offset(0);
        make.size.mas_equalTo(CGSizeMake(200, 20));
    }];
    
    lable1.text = @"马上去其他地方逛逛吧";
    lable1.textColor = [UIColor blackColor];
    lable1.font = [UIFont systemFontOfSize:15];
    lable1.textAlignment = NSTextAlignmentCenter;
}






#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.itemsAry.count;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    PostModel * postModel;
    PostReplyModel *postReplyModel;
    if (self.type == 0) {
        postModel  = [self.itemsAry objectAtIndex:section];
        if (postModel.imgAry.count > 0) {
            return 4;
        }else{
            return 3;
        }
    }else if (self.type == 1 || self.type == 2||self.type == 3 || self.type == 4){
        postReplyModel  = [self.itemsAry objectAtIndex:section];
        return 3;
    }else{
        return 4;
    }
    
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostModel * postModel;
    PostReplyModel *postReplyModel;
    
    
    PostTitleCell *cell0 = [PostTitleCell cellWithTableView:tableView];
    
    
    PostContentCel *cell1 = [PostContentCel cellWithTableView:tableView];
   
    
    PostPictureCell *cell2 = [PostPictureCell cellWithTableView:tableView];
    
    
    
    
    PostReplyCell *cell3 = [PostReplyCell cellWithTableView:tableView];
    
    
    
    PostReplyPictureCell *cell4 = [PostReplyPictureCell cellWithTableView:tableView];
    
    
    CommentBottomCell *cell5 = [CommentBottomCell cellWithTableView:tableView];

    if (self.type == 0) {
       postModel  = [self.itemsAry objectAtIndex:indexPath.section];
        cell0.postModel = postModel;
        cell1.postModel = postModel;
        cell2.postModel = postModel;
        cell3.postModel = postModel;
        cell4.postModel = postModel;
        cell5.postModel = postModel;
        
    }else if (self.type == 1 ||self.type == 2|| self.type == 3 || self.type == 4){
       postReplyModel  = [self.itemsAry objectAtIndex:indexPath.section];
        cell0.postReplyModel = postReplyModel;
        cell1.postReplyModel = postReplyModel;
        cell2.postReplyModel = postReplyModel;
        cell3.postReplyModel = postReplyModel;
        cell4.postReplyModel = postReplyModel;
        if (self.type == 2 || self.type == 4) {
            cell0.nickLabel.text = postReplyModel.post_author;
            cell0.createTimeLabel.text = postReplyModel.post_dateline_show;
            postReplyModel.thread_subject = postReplyModel.post_message;
            cell2.postReplyModel = postReplyModel;
//            NSString * string =  [NSString stringWithFormat:@"原帖：%@", postReplyModel.post_message];
//            NSMutableAttributedString *attr = [ZKTextImgReplaceHandle handleText:string withRegex:nil];
//            if (attr) {
//                cell1.lable.attributedText = attr;
//            } else {
//                cell1.lable.text = string;
//            }

            
        }
    }
    
    
    
    if (indexPath.row == 0) {
        return cell0;
    }else if (indexPath.row == 1){
        return cell1;
    }
    
    if (self.type == 0) {
        
        if (postModel.imgAry.count > 0) {
            if (indexPath.row == 2) {
                return cell2;
            }else if (indexPath.row == 3){
                return cell5;
            }else{
                return cell5;
            }
            
        }else{
            
            if (indexPath.row == 2) {
                return cell5;
            }else{
                return cell5;
            }
        }
    }else if (self.type == 1 || self.type == 3){
    
        if (postReplyModel.img.count > 0) {
            return cell4;
        }else{
            return cell3;
        }
        
    }else if (self.type == 2 || self.type == 4){
        NSString * string =  [NSString stringWithFormat:@"评论帖子：%@", postReplyModel.comment_comment];
        NSMutableAttributedString *attr = [ZKTextImgReplaceHandle handleText:string withRegex:nil];
        if (attr) {
            cell3.lable.attributedText = attr;
        } else {
            cell3.lable.text = string;
        }
        return cell3;
        
    }else{
        return cell1;
    }
    
    
    
    
    
}

// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PostModel * postModel;
    PostReplyModel *postReplyModel;
    if (indexPath.row == 0) {
        return 48;
    }else if (self.type == 0){
        
        postModel = [self.itemsAry objectAtIndex:indexPath.section];
        if (indexPath.row == 1) {
            NSString * string =  [NSString stringWithFormat:@"原帖：%@", postModel.subject];
           // CGFloat  height = [string  getBoundingRectOfStringSize:CGSizeMake(SCREEN_WIDTH - 26, 10000) font:12].size.height;
            CGFloat  height = [ZKTextImgReplaceHandle getImgTextHeightWithText:string regex:nil size:CGSizeMake(SCREEN_WIDTH - 26, 10000) fontSize:16];
            return height + 4;
        }
        

        if (postModel.imgAry.count > 0) {
            if (indexPath.row == 2) {
            
               
               CGFloat width = (SCREEN_WIDTH - Margin * 4) / 3;
               CGFloat y = Margin * ((postModel.imgAry.count - 1) / 3) + width * ((postModel.imgAry.count - 1) / 3 + 1);
               return y + 5;
                
            }else if (indexPath.row == 3){
                
                return 30;
                
            }else{
                return 30;
            }
           
        }else {
            
            return 30;
            
        }
    
    }else if (self.type == 1|| self.type == 2||self.type == 3 || self.type == 4){
        
        postReplyModel = [self.itemsAry objectAtIndex:indexPath.section];
        
        if (indexPath.row == 1) {
            NSString * string;
            if (self.type == 1 || self.type == 3) {
                string =  [NSString stringWithFormat:@"原帖：%@", postReplyModel.thread_subject];
            }else{
                string =  [NSString stringWithFormat:@"原帖：%@", postReplyModel.post_message];
            }
            
            
            //CGFloat  height = [string  getBoundingRectOfStringSize:CGSizeMake(SCREEN_WIDTH - 32, 10000) font:12].size.height;
            CGFloat  height = [ZKTextImgReplaceHandle getImgTextHeightWithText:string regex:nil size:CGSizeMake(SCREEN_WIDTH - 32, 10000) fontSize:16];
            NSLog(@"%f", height);
            return height + 4;
        }
        if (indexPath.row == 2) {

            if (self.type == 1 || self.type == 3) {
                
                NSString * string =  [NSString stringWithFormat:@"回复帖子：%@", postReplyModel.post_message];
                
                 //CGFloat  height = [string  getBoundingRectOfStringSize:CGSizeMake(SCREEN_WIDTH - 32, 10000) font:12].size.height;
                
                CGFloat  height = [ZKTextImgReplaceHandle getImgTextHeightWithText:string regex:nil size:CGSizeMake(SCREEN_WIDTH - 32, 10000) fontSize:16];
                
                
                if (postReplyModel.img.count > 0) {
                    
                    
                    CGFloat width = (SCREEN_WIDTH - Margin * 2 - LeftMargin * 2) / 3;
                    CGFloat y = Margin * ((postReplyModel.img.count - 1) / 3) + width * ((postReplyModel.img.count - 1) / 3 + 1);
                
                    return y + height + 25;
                    
                }else{
                    
                    return 20 + height;
                }

            }else if (self.type == 2 || self.type == 4){
                NSString * string =  [NSString stringWithFormat:@"评论：%@", postReplyModel.comment_comment];
                //CGFloat  height = [string  getBoundingRectOfStringSize:CGSizeMake(SCREEN_WIDTH - 26, 10000) font:12].size.height;
                CGFloat  height = [ZKTextImgReplaceHandle getImgTextHeightWithText:string regex:nil size:CGSizeMake(SCREEN_WIDTH - 26, 10000) fontSize:16];
                 return 20 + height;
            }else{
                return 30;
            }
        }else{
            return 30;
        }
        
    }else{
        return 30;
    }
    
}

// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}

// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    
    PostModel * postModel;
    PostReplyModel *postReplyModel;
    
    if (self.type == 0) {
        
        
        
        postModel = [self.itemsAry objectAtIndex:indexPath.section];
        if ([postModel.status integerValue] == 1) {
            
            PostDetailVC *vc = [[PostDetailVC alloc] init];
            vc.tid = postModel.tid;
            vc.fid = postModel.fid;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            [SVProgressHUD showOnlyStatus:@"帖子已被删除" withDuration:1];
        }

        

        
    }else {
        
        
        postReplyModel = [self.itemsAry objectAtIndex:indexPath.section];

        if ([postReplyModel.post_status integerValue] == 1 && [postReplyModel.thread_status integerValue] == 1) {
            
            PostDetailVC *vc = [[PostDetailVC alloc] init];
            vc.tid = postReplyModel.tid;
            vc.fid = postReplyModel.fid;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            [SVProgressHUD showOnlyStatus:@"帖子已被删除" withDuration:1];
            
            
        }
       
    }
        
        
}



#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
